package com.epfresh.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Process;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.epfresh.BuildConfig;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.constant.Constant;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.api.utils.ToastUtils;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.BaseApplication;
import com.epfresh.global.DataManager;
import com.epfresh.global.MessageCentre;
import com.epfresh.utils.DataCleanManager;
import com.google.gson.Gson;
import com.epfresh.R;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class SetActivity extends BaseActivity {

    static final String TAG = "SetActivity";
    	private TextView passwordTv;
    /*   private TextView oftenQuestion;
       private TextView quit,;*/
    double sizeDouble = 0;
    TextView tvClear, tvSize ,feedback;
    TextView tvCrash;
    TextView tvServe, tvGoEvaluate, tvAbout, tvRenew;
    Button btQuit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set);
        tvSize = (TextView) findViewById(R.id.tv_size);
        tvClear = (TextView) findViewById(R.id.tv_clear);
        tvSize.setOnClickListener(this);
        tvClear.setOnClickListener(this);
        tvAbout = (TextView) findViewById(R.id.tv_about);
        tvAbout.setOnClickListener(this);
        tvServe = (TextView) findViewById(R.id.tv_serve);
        tvServe.setOnClickListener(this);
        tvGoEvaluate = (TextView) findViewById(R.id.tv_go_evaluate);
        tvGoEvaluate.setOnClickListener(this);
        tvRenew = (TextView) findViewById(R.id.tv_renew);
        tvRenew.setOnClickListener(this);
        btQuit = (Button) findViewById(R.id.bt_quit);
        btQuit.setOnClickListener(this);

		passwordTv = (TextView)findViewById(R.id.set_password);
        passwordTv.setOnClickListener(this);
        tvCrash = (TextView) findViewById(R.id.tv_crash);
        int env0 = ApplicationHelper.getInstance().getEnv();
        if (env0 == 0) {
            tvCrash.setText("切换环境(当前是正式环境)");
        } else if (env0 == 1) {
            tvCrash.setText("切换环境(当前是预发布环境)");
        } else if (env0 == 2) {
            tvCrash.setText("切换环境(当前是测试环境)");
        } else if (env0 == 3) {
            tvCrash.setText("切换环境(当前是开发环境)");
        }

        int env = BuildConfig.ENV;

        if (env == 0){//正式版本
            findViewById(R.id.v_env).setVisibility(View.GONE);
        }else if (env > 0){//测试版本
            findViewById(R.id.v_env).setVisibility(View.VISIBLE);

            findViewById(R.id.tv_rp).setOnClickListener(this);
            findViewById(R.id.tv_rc).setOnClickListener(this);
            findViewById(R.id.tv_beta).setOnClickListener(this);
            findViewById(R.id.tv_dev).setOnClickListener(this);
        }
        feedback = (TextView)findViewById(R.id.feedback);
        feedback.setOnClickListener(this);
        File flag2 = mContext.getExternalCacheDir();//缓存
        if (flag2 != null) {
            Log.e("文件夹名称：", "" + flag2.toString());
            try {
                sizeDouble = DataCleanManager.getFolderSize(flag2);///xiaomi4lte 报异常
                Log.i("本地图片：", "" + DataCleanManager.getFolderSize(flag2));///xiaomi4lte 报异常
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        tvSize.setText(DataCleanManager.getFormatSize(sizeDouble));
        initView();

    }

    private void initView() {
        ivBack.setVisibility(View.VISIBLE);
        basetitle.setText("设置");
    }

    public static void delete(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }

        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                file.delete();
                return;
            }

            for (int i = 0; i < childFiles.length; i++) {
                delete(childFiles[i]);
            }
            file.delete();
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_size:
            case R.id.tv_clear:
                DataCleanManager.cleanExternalCache();
                DataCleanManager.cleanInternalCache();
                ToastUtils.ImageToast(this, R.mipmap.progress_ok, BaseApplication.getDoc().getCleared());
                tvSize.setClickable(false);
                tvClear.setClickable(false);
                tvAbout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tvClear.setClickable(true);
                        tvSize.setClickable(true);
                    }
                }, 2000);
                tvSize.setText("0.0MB");
                break;
            case R.id.tv_serve:
                Intent intent = new Intent(this, WebActivity.class);
                intent.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_PUR_AGREEMENT);
                intent.putExtra(Constant.KEY_WEB_TITLE, "帮助");
                startActivity(intent);
                break;
            case R.id.tv_go_evaluate:
                evaluate();
                break;
            case R.id.tv_about:
                Intent about = new Intent(this, AboutActivity.class);
                startActivity(about);
                break;
            case R.id.tv_renew:
                //检查版本更新
                if(ApplicationHelper.getInstance().isDownloadApk){
                    T.toast("下载中，请稍等");
                    return;
                }
                ApplicationHelper.getInstance().updateVersion(true,this);
                break;
            case R.id.bt_quit:
                logout();
                break;
            case R.id.tv_rp://生产
                switchAppRuntime(0);
                break;
            case R.id.tv_rc://fort
                switchAppRuntime(1);
                break;
            case R.id.tv_beta://beta
                switchAppRuntime(2);
                break;
            case R.id.tv_dev://开发
                switchAppRuntime(3);
                break;
            case R.id.set_password:
                Intent password = new Intent(this, ForgetPasdActivity.class);
                startActivity(password);
                break;
			case R.id.feedback:
				Intent feedback = new Intent(getBaseContext(), MyFeedBackActivity.class);
				startActivity(feedback);
				break;
/*				case R.id.often_qustion:
				Intent often = new Intent(getBaseContext(), QuestionActivity.class);
				startActivity(often);
				break;*/

            default:
                break;
        }
    }

    private void switchAppRuntime(int env) {
        //注销用户
        clearUser();
        //注销店铺信息
        ApplicationHelper.getInstance().switchEnv(env);
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        Process.killProcess(Process.myPid());
//        Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
//
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//
//        startActivity(intent);
    }
    void evaluate() {//简易型市场评分
        Uri uri = Uri.parse("market://details?id=" + getPackageName());
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
/*

	void goEvaluate() {
// 判断360市场是否存在
		if (isAvilible(this, "com.qihoo.appstore")) {
// 市场存在
			Intent intent = new Intent(Intent.ACTION_VIEW);
// 跳转到360市场评分
			ComponentName cn = new ComponentName("com.qihoo.appstore",
					"com.qihoo.appstore.activities.SearchDistributionActivity");
			intent.setComponent(cn);
			intent.setData(Uri
					.parse("market://details?id=com.paopaobeauty.meinv"));
			startActivity(intent);
		} else {
// 市场不存在
			T.toast("请下载360手机助手");
		}
	}


	// 判断市场是否存在的方法
	public static boolean isAvilible(Context context, String packageName) {
		final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
		List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
		List<String> pName = new ArrayList<String>();// 用于存储所有已安装程序的包名
// 从pinfo中将包名字逐一取出，压入pName list中
		if (pinfo != null) {
			for (int i = 0; i < pinfo.size(); i++) {
				String pn = pinfo.get(i).packageName;
				pName.add(pn);
			}
		}
		return pName.contains(packageName);// 判断pName中是否有目标程序的包名，有TRUE，没有FALSE

	}
*/

    private void logout() {
        RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
        data.setCmd(AppPurchaseRouterConstant.cmd_account_acc_logout);
        //data.setToken(getUser().getToken());
        Map<String, String> map = new HashMap<>();
        map.put("accountId", getUser().getAccountId());
        map.put("clientId", "purchase-android");
        map.put("clientSecret", "purchase-android-secret");
        map.put("accessToken", getUser().getAccess_token());
        data.setParameters(map);
        request(data, AppPurchaseRouterConstant.cmd_account_acc_logout, onRequestCodeListener);
    }

    OnRequestListener<StatusEntity> onRequestCodeListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            logoutSuccess();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            logoutSuccess();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }
        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            hideProgressDialog();
            logoutSuccess();
            DataManager.getInstance().updateCartCnt();
        }
    };


    public void logoutSuccess(){
        MessageCentre.getInstance().logoutAlias();
        SharedPreferences user = mContext.getSharedPreferences(
                "userinfo", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = user.edit();
        editor.putString("password", "");
        editor.putString("accountId", "");
        editor.putString("access_token", "");
        editor.commit();
        clearUser();
        MessageCentre.getInstance().logoutAlias();
        T.toast("已退出");
        Intent main = new Intent(getBaseContext(), HomeActivity.class);
        main.putExtra("home_tab_index",0);
        main.putExtra("refreshFlag","refreshHomeFrag");
        startActivity(main);
        finish();
    }
}
